#!/bin/zsh -f
# FileWave KB666 macOS Client uninstaller 4.2.0 — Fileset main payload FW755246D
# Based on the audited 4.1.2 offboarding scripts by Sean Holden / FileWave KB.
# Removes the Client and its separate Upgrader together; retains logs. Does not
# remove deployed customer files, MDM enrollment, or server-side records.
# Always retain /var/log/fwcld-upgrader.log. See operator preflight before use.
# Operator prerequisites (both delivery methods): confirm this Mac is being
# permanently retired as a Client. Use independent management access. Verify no
# Server, Booster, Central or other FileWave role, including unreceipted roles.
# Check upgrade assignments/queue in management and the configured local Client
# data location. Stop scheduling new work by your approved change process; keep
# concurrent installers, downloads, retries and rollbacks out of this window.
# Review installer/upgrader activity and logs; if this is unknown, DO NOT RUN.
# Do not delete markers, unload installers, or change permissions to pass guards.
# Local snapshots do not prove there is no pending upgrade. Run only a verified
# root-controlled script copy. Capture output independently of the retiring Client.
# On STOP, keep the receipts, logs and device record; do not automatically rerun.
# KB666 v4.2.0 — permanent Client-only offboarding, not upgrade repair.
# Required before invocation: retire upgrade assignments, quiesce all installer
# sources, verify the configured data path and no pending/running work. Local
# checks cannot determine server intent or exclude a concurrent root installer.
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
readonly TRUST_ROOT=/
readonly TRUST_UID=0
readonly WHEEL_GID=0 ADMIN_GID=80
readonly MAIN=com.filewave.fwcld.pkg UP=com.filewave.fwcld-upgrader UP_PKG=com.filewave.fwcld-upgrader.pkg
readonly PL=/Library/LaunchDaemons/com.filewave.fwcld-upgrader.plist
readonly APP=/usr/local/sbin/fwcld-upgrader.app
readonly EXE=$APP/Contents/MacOS/fwcld-upgrader
readonly JOB=system/$UP
stop() { print -ru2 -- "STOP: $*; preserve diagnostics and review before retrying."; exit 1; }
# BSD stat defaults to lstat. Only a precise ENOENT diagnostic proves absence;
# permission, I/O, malformed or unexpected errors must not authorize a forget.
present() {
    local out rc
    out=$(/usr/bin/stat -f %p "$1" 2>&1); rc=$?
    (( rc == 0 )) && return 0
    if (( rc == 1 )) && [[ $out == "stat: $1: stat: No such file or directory" ]]; then return 1; fi
    stop "cannot inspect $1 ($rc): $out"
}
# Validate ancestors one component at a time; never resolve an alias/symlink.
# Directory trust includes owner, write bits and extended ACLs. Refusal on
# writable Homebrew prefixes etc. is intentional; never repair permissions.
trust_node() {
    local meta listing gid
    [[ ! -L $1 ]] || stop "symlink: $1"
    meta=$(/usr/bin/stat -f '%u:%p' "$1") || stop "stat: $1"
    [[ ${meta%%:*} == $TRUST_UID && ${meta#*:} == <-> ]] || stop "untrusted owner/type: $1"
    if (( (8#${meta#*:} & 8#022) != 0 )); then
        case $1 in /Library|/Applications|/Applications/FileWave|/usr/local/etc)
            gid=$(/usr/bin/stat -f %g "$1") || stop "group: $1"
            [[ -d $1 && ( $gid == $WHEEL_GID || $gid == $ADMIN_GID ) ]] && (( (8#${meta#*:} & 8#7777) == 8#775 )) || stop "writable: $1";;
            *) stop "writable: $1";;
        esac
    fi
    listing=$(/bin/ls -lde "$1") || stop "ACL inspection: $1"
    [[ $listing != *' allow '* ]] || stop "allow ACL: $1"
}
trust_chain() {
    local p=$1
    [[ $p == $TRUST_ROOT || $p == ${TRUST_ROOT%/}/* ]] || stop "non-absolute or untrusted path: $p"
    if [[ $p != $TRUST_ROOT ]]; then
        trust_chain "${p:h}"
        if present "${p:h}"; then [[ -d ${p:h} ]] || stop "non-directory ancestor: ${p:h}"; fi
    fi
    if present "$p"; then trust_node "$p"; fi
    return 0
}
inventory() {
    local out
    out=$(/usr/sbin/pkgutil --pkgs) || stop 'receipt inventory failed'
    [[ -n $out ]] || stop 'empty receipt inventory'
    receipts=("${(@f)out}")
    local id
    for id in "${receipts[@]}"; do [[ -n $id && $id != *[[:cntrl:]]* ]] || stop 'malformed receipt inventory'; done
}
has_receipt() { (( ${receipts[(Ie)$1]} > 0 )); }
process_absent() {
    /usr/bin/pgrep -x "$1" >/dev/null
    case $? in 1) return 0;; 0) stop "active process: $1";; *) stop "process inventory: $1";; esac
}
quiescent() {
    local lock=/private/var/FileWave/upgrade_in_progress.lock p=/private/var/FileWave/upgrade_scheduled.json sched version stamp now
    trust_chain "$lock"; present "$lock" && stop "upgrade lock: $lock"
    trust_chain "${p:h}"
    if present "$p"; then
        # This vendor-created file may be 0666. Read only as an additional veto,
        # never as authority that the management-side upgrade queue is clear.
        [[ ! -L $p && $(/usr/bin/stat -f '%u:%l' "$p") == "$TRUST_UID:1" && -f $p ]] || stop "invalid scheduling marker: $p"
        sched=$(/usr/bin/plutil -extract scheduled_for_upgrade raw -expect bool -o - "$p") && [[ $sched == false ]] || stop 'scheduled or unrecognized upgrade state'
        version=$(/usr/bin/plutil -extract available_client_version raw -expect string -o - "$p") || stop 'invalid scheduling marker version'
        stamp=$(/usr/bin/stat -f %m "$p") && now=$(/bin/date +%s) && [[ $stamp == <-> && $now == <-> ]] || stop 'scheduling marker timestamp unavailable'
        [[ $stamp -le $now ]] && { [[ -z $version ]] || (( now - stamp < 7200 )); } || stop 'stale or future scheduling marker (self-check possible)'
    fi
    process_absent installer
    process_absent Installer
}
check_roles() {
    local p id
    for id in com.filewave.fwserver.pkg com.filewave.fwbooster.pkg com.filewave.admin.pkg com.filewave.admin2.pkg; do
        has_receipt "$id" && stop "co-installed receipt $id"
    done
    for id in "${receipts[@]}"; do
        case $id in "$UP"|"$UP_PKG"|"$MAIN") ;; com.filewave.*) stop "unclassified FileWave receipt: $id";; esac
    done
    for p in /Library/LaunchDaemons/com.filewave.server.plist /Library/LaunchDaemons/com.filewave.fwbooster.plist /Library/LaunchDaemons/com.filewave.nats-booster.plist /usr/local/sbin/fwbooster /usr/local/filewave/OSS-server.txt; do
        trust_chain "$p"; present "$p" && stop "possible other role: $p"
    done
    for p in '/Applications/FileWave/FileWave Admin.app' '/Applications/FileWave/Booster Monitor.app'; do
        # Read-only role sentinels, never removal targets. /Applications may be admin writable.
        trust_chain "${p:h}"
        present "$p" && stop "possible other role: $p"
    done
    return 0
}
job_state() {
    local out rc
    out=$(/bin/launchctl print "$JOB" 2>&1); rc=$?
    if (( rc == 0 )); then
        [[ $out == "$JOB = {"$'\n'* && $'\n'$out$'\n' == *$'\n\tpath = '"$PL"$'\n'* && $'\n'$out$'\n' == *$'\n\tprogram = '"$EXE"$'\n'* ]] || stop "unrecognized loaded job: $JOB"
        job=loaded
    elif (( rc == 113 )) && [[ $out == $'Bad request.\nCould not find service "'"$UP"'" in domain for system' || $out == 'Could not find service "'"$UP"'" in domain for system' ]]; then
        job=absent
    else stop "unknown launchd result ($rc): $out"; fi
}
tree_check() {
    local bad dirs dir device dev
        # find -P/-x never follows symbolic links or descends through mounts.
        # Refuse unusual names, unsafe directory ownership/ACLs and mount points
        # before deletion. Unlink internal bundle symlinks; never visit targets.
        bad=$(/usr/bin/find -P -x "$1" -name $'*\n*' -exec /bin/echo invalid \;) || stop 'cannot inventory bundle'
        [[ -z $bad ]] || stop 'unexpected bundle pathname'
        dirs=$(/usr/bin/find -P -x "$1" -type d -print) || stop 'cannot inspect bundle directories'
        device=$(/usr/bin/stat -f %d "${1:h}") || stop 'cannot identify parent device'
        for dir in "${(@f)dirs}"; do
            trust_node "$dir"; dev=$(/usr/bin/stat -f %d "$dir") && [[ $dev == $device ]] || stop "mounted bundle subtree: $dir"
        done
}
check_up_files() {
    local value dirs dir dev device bad
    local legacy=/System/Library/LaunchDaemons/com.filewave.fwcld-upgrader.plist
    trust_chain "$legacy"; present "$legacy" && stop "unreviewed legacy LaunchDaemon: $legacy"
    trust_chain "$PL"; trust_chain "$APP"
    if present "$PL"; then
        [[ -f $PL ]] || stop "not a plist file: $PL"
        value=$(/usr/bin/plutil -extract Label raw -o - "$PL") && [[ $value == $UP ]] || stop 'upgrader plist Label mismatch'
        value=$(/usr/bin/plutil -extract ProgramArguments.0 raw -o - "$PL") && [[ $value == $EXE ]] || stop 'upgrader plist executable mismatch'
        # Program overrides argv[0] in launchd. Only the packaged argv shape is accepted.
        value=$(/usr/bin/plutil -extract ProgramArguments raw -o - "$PL") && [[ $value == 1 ]] || stop 'unexpected upgrader arguments'
        if /usr/bin/plutil -extract Program xml1 -o - "$PL" >/dev/null 2>&1; then stop 'unexpected Program key'; fi
    fi
    if present "$APP"; then
        [[ -d $APP ]] || stop "not a bundle: $APP"
        trust_chain "$APP/Contents/Info.plist"; trust_chain "$EXE"
        [[ -f $APP/Contents/Info.plist && -f $EXE && -x $EXE ]] || stop 'incomplete upgrader bundle'
        value=$(/usr/bin/plutil -extract CFBundleIdentifier raw -o - "$APP/Contents/Info.plist") && [[ $value == $UP ]] || stop 'upgrader bundle identifier mismatch'
        value=$(/usr/bin/plutil -extract CFBundleExecutable raw -o - "$APP/Contents/Info.plist") && [[ $value == fwcld-upgrader ]] || stop 'upgrader bundle executable mismatch'
        tree_check "$APP"
    fi
}
upgrader_absent() {
    inventory; check_roles
    if has_receipt "$UP" || has_receipt "$UP_PKG"; then stop 'upgrader receipt reappeared'; fi
    trust_chain "$APP"; trust_chain "$PL"
    if present "$APP" || present "$PL"; then stop 'upgrader payload reappeared'; fi
    job_state; [[ $job == absent ]] || stop 'upgrader job reappeared'
    process_absent fwcld-upgrader
}
retire_upgrader() {
    local bom line id
    local -a owned members
    for id in "$UP_PKG" "$UP"; do
        has_receipt "$id" || continue
        owned+=("$id"); members=()
        bom=$(/usr/sbin/pkgutil --files "$id") || stop 'upgrader BOM unavailable'
        for line in "${(@f)bom}"; do
            line=${line#./}
            [[ /$line/ != */../* && $line != *[[:cntrl:]]* ]] || stop "invalid upgrader BOM: $id"
            case $line in
                .|Library|Library/LaunchDaemons|Library/LaunchDaemons/com.filewave.fwcld-upgrader.plist|usr|usr/local|usr/local/sbin|usr/local/sbin/fwcld-upgrader.app|usr/local/sbin/fwcld-upgrader.app/*) members+=("$line");;
                *) stop "mixed or unexpected upgrader receipt $id: $line";;
            esac
        done
        for line in Library/LaunchDaemons/com.filewave.fwcld-upgrader.plist usr/local/sbin/fwcld-upgrader.app/Contents/Info.plist usr/local/sbin/fwcld-upgrader.app/Contents/MacOS/fwcld-upgrader; do
            (( ${members[(Ie)$line]} )) || stop "upgrader BOM does not identify $line"
        done
    done
    check_up_files; job_state
    if (( ! ${#owned} )) && { present "$APP" || present "$PL" || [[ $job == loaded ]]; }; then stop 'unreceipted upgrader artifacts'; fi
    if [[ $job == loaded ]]; then
        [[ -f $PL && -x $EXE ]] || stop 'loaded job lacks verified payload'
        quiescent
        /bin/launchctl bootout "$JOB" || stop 'upgrader bootout failed'
        local n
        for n in {1..12}; do job_state; [[ $job == absent ]] && break; /bin/sleep 0.25; done
    fi
    job_state; [[ $job == absent ]] || stop 'upgrader still loaded'
    process_absent fwcld-upgrader; quiescent; check_up_files
    if present "$APP"; then /usr/bin/find -P -x "$APP" -depth -delete || stop 'bundle removal failed'; fi
    if present "$PL"; then /bin/rm -- "$PL" || stop 'plist removal failed'; fi
    job_state; [[ $job == absent ]] || stop 'upgrader reloaded'
    process_absent fwcld-upgrader
    if present "$APP" || present "$PL"; then stop 'upgrader files remain'; fi
    quiescent
    for id in "${owned[@]}"; do
        /usr/sbin/pkgutil --forget "$id" || stop "upgrader receipt forget failed: $id"
        inventory; has_receipt "$id" && stop "upgrader receipt remains: $id"
    done
    inventory
    if has_receipt "$UP" || has_receipt "$UP_PKG"; then stop 'upgrader receipt reappeared'; fi
    return 0
}

# Only these previously selected Client receipt entries can authorize a removal.
# Do not construct privileged removal targets from arbitrary BOM suffix matches.
client_bom() {
    local bom line item anchor=0
    bom=$(/usr/sbin/pkgutil --files "$MAIN") && [[ -n $bom ]] || stop 'main receipt file inventory unavailable'
    for line in "${(@f)bom}"; do
        [[ $line != /* && /$line/ != */../* ]] || stop 'unsafe main receipt entry'
        item="/${line#./}"
        case $item in
            /usr/local/sbin/FileWave.app|/Library/LaunchDaemons/com.filewave.fwcld.plist) (( anchor++ ));;
            /usr/local/sbin/Client\ Assistant.app|/Library/LaunchAgents/com.filewave.kiosk2.plist|/Library/Frameworks/FileWaveCore.framework|/Library/LaunchAgents/com.filewave.fwGUI.plist|/Library/LaunchDaemons/com.filewave.fwVNCServer.plist|/usr/local/bin/fwcontrol|/usr/local/share/man/man1/fwcontrol.1|/usr/local/sbin/filewave-vnc-server) ;;
            /usr/local/sbin/FileWave.app/*|/usr/local/sbin/Client\ Assistant.app/*|/Library/Frameworks/FileWaveCore.framework/*) continue;;
            */FileWave.app|*/com.filewave.fwcld.plist|*/FileWaveCore.framework|*/com.filewave.fwGUI.plist|*/com.filewave.fwVNCServer.plist|*/fwcontrol|*/fwcontrol.1|*/filewave-vnc-server) stop "unexpected Client receipt path: $item";;
            *) continue;;
        esac
        client_files+=("$item")
    done
    (( anchor )) || stop 'main receipt lacks Client anchor'
}
# Exact paths. No prefix glob for fwcld: the old prefix also erased the separate upgrader log.
client_plan() {
    local dir p home
    client_files=(); data_leaves=(); client_bom
    client_files+=(/usr/local/etc/fwcld.plist /Library/Preferences/com.filewave.plist /Library/Preferences/com.filewave.WinClient.plist /Library/Preferences/com.filewave.Client.plist /usr/local/etc/.fwVNCServerAuth /usr/local/etc/engagex.plist /usr/local/etc/fwkiosk_settings.ini)
    # Never traverse home directories or remove diagnostic logs. A writable
    # Client cache directory is retained rather than recursively modified.
    dir=/private/var/FileWave
    trust_chain "$dir"
    for p in "$dir"/*(N); do
        case ${p:t} in upgrade_scheduled.json|upgrade_in_progress.lock|*log*|trust_store) continue;; esac
        if [[ -f $p && ! -L $p && $(/usr/bin/stat -f %u "$p") == $TRUST_UID ]]; then
            data_leaves+=("$p")
        else print -- "Retain unselected Client state: $p"; fi
    done
    for p in /Library/LaunchAgents/com.filewave.kiosk2.plist /Library/LaunchDaemons/com.filewave.fwcld.plist /Library/LaunchAgents/com.filewave.fwGUI.plist /Library/LaunchDaemons/com.filewave.fwVNCServer.plist '/usr/local/sbin/Client Assistant.app' /usr/local/sbin/FileWave.app; do
        trust_chain "$p"
        if present "$p" && (( ! ${client_files[(Ie)$p]} )); then stop "not in Client BOM: $p"; fi
    done
    for p in "${client_files[@]}"; do
        trust_chain "$p"
        if [[ -d $p ]]; then tree_check "$p"; fi
    done
    p='/usr/local/sbin/Client Assistant.app'
    if present "$p"; then
        trust_chain "$p/Contents/Info.plist"
        [[ -f "$p/Contents/MacOS/Client Assistant" && ! -L "$p/Contents/MacOS/Client Assistant" && $(/usr/bin/plutil -extract CFBundleExecutable raw -o - "$p/Contents/Info.plist") == 'Client Assistant' ]] || stop 'unrecognized Client Assistant'
    fi
    # Only remove a legacy Applications Kiosk when its own bundle ID agrees.
    p='/Applications/FileWave Kiosk.app'; trust_chain "$p"
    if present "$p"; then
        trust_chain "$p/Contents/Info.plist"
        [[ -d $p && $(/usr/bin/plutil -extract CFBundleIdentifier raw -o - "$p/Contents/Info.plist") == com.filewave.kiosk2 ]] || stop 'unrecognized Applications Kiosk'
        tree_check "$p"; client_files+=("$p")
    fi
}
# Discover possible GUI domains across console/fast-user-switch/network logins
# from SystemConfiguration console sessions; background service accounts do not have GUI domains.
client_job() {
    local service=$1 file=${2:-} exe=${3:-} out rc label=${1:t} domain=${1:h} absent_message no_domain
    if [[ $domain == system ]]; then absent_message="Could not find service \"$label\" in domain for system"; else absent_message="Could not find service \"$label\" in domain for user gui: ${domain:t}"; fi
    no_domain="Could not find domain for user gui: ${domain:t}"
    out=$(/bin/launchctl print "$service" 2>&1); rc=$?
    if (( rc == 0 )); then
        [[ $out == "$service = {"$'\n'* ]] || stop "unrecognized job listing: $service"
        if [[ -n $file ]]; then
            [[ -f $file && $'\n'$out$'\n' == *$'\n\tpath = '"$file"$'\n'* && $'\n'$out$'\n' == *$'\n\tprogram = '"$exe"$'\n'* ]] || stop "unrecognized job identity: $service"
        fi
        cj=loaded
    elif (( rc == 113 )) && [[ $out == "$absent_message" || $out == $'Bad request.\n'"$absent_message" ]]; then cj=absent
    elif [[ $domain == gui/* ]] && (( rc == 112 )) && [[ $out == "$no_domain" || $out == $'Bad request.\n'"$no_domain" ]]; then cj=absent
    else stop "unknown launchd result ($rc) for $service: $out"; fi
}
client_jobs() {
    local operation=$1 raw uid service file exe label target value
    local -a domains; local -aU uids
    local row console listed=0
    console=$(/usr/bin/stat -f %u /dev/console) && [[ $console == <-> ]] || stop 'console owner unavailable'
    raw=$(print -r -- 'show State:/Users/ConsoleUser' | /usr/sbin/scutil) || stop 'session inventory unavailable'
    if [[ $raw == *'SessionInfo : <array> {'* ]]; then
        for row in "${(@f)raw}"; do
            [[ $row == *'kCGSSessionUserIDKey : '* ]] || continue
            uid=${row##*: }; [[ $uid == <-> ]] || stop 'malformed session inventory'
            (( listed++ )); (( uid == 0 )) || uids+=("$uid")
        done
        (( listed )) || stop 'empty GUI session inventory'
    elif [[ $console != 0 || ( $raw != *'No such key'* && $raw != *'Name : loginwindow'* ) ]]; then stop 'unknown GUI session state'; fi
    (( console == 0 || ${uids[(Ie)$console]} )) || stop 'console user missing from GUI session inventory' 
    for label in com.filewave.fwcld com.filewave.kiosk2 com.filewave.fwGUI com.filewave.fwVNCServer; do
        case $label in
            com.filewave.fwcld) exe=/usr/local/sbin/FileWave.app/Contents/MacOS/fwcld;;
            com.filewave.kiosk2) exe='/usr/local/sbin/FileWave.app/Contents/MacOS/FileWave Kiosk.app/Contents/MacOS/FileWave Kiosk';;
            com.filewave.fwGUI) exe=/usr/local/sbin/FileWave.app/Contents/Resources/fwGUI.app/Contents/MacOS/fwGUI;;
            *) exe=/usr/local/sbin/filewave-vnc-server;;
        esac
        case $label in
            com.filewave.kiosk2|com.filewave.fwGUI) file=/Library/LaunchAgents/$label.plist; domains=(); for uid in "${uids[@]}"; do domains+=("gui/$uid"); done;;
            *) file=/Library/LaunchDaemons/$label.plist; domains=(system);;
        esac
        if present "$file"; then
            value=$(/usr/bin/plutil -extract Label raw -o - "$file") && [[ $value == $label ]] || stop "Client plist label: $file"
            value=$(/usr/bin/plutil -extract ProgramArguments.0 raw -o - "$file") && [[ $value == $exe ]] || stop "Client plist executable: $file"
            if /usr/bin/plutil -extract Program xml1 -o - "$file" >/dev/null 2>&1; then stop "unexpected Program: $file"; fi
        fi
        for target in "${domains[@]}"; do
            service="$target/$label"; client_job "$service" "$file" "$exe"
            if [[ $cj == loaded ]]; then
                case $operation in
                    check) ;;
                    unload) /bin/launchctl bootout "$service" || stop "Client bootout failed: $service"
                        local n
                        for n in {1..12}; do client_job "$service" "$file" "$exe"; [[ $cj == absent ]] && break; /bin/sleep 0.25; done;;
                    absent) stop "Client service remains: $service";;
                esac
            fi
        done
    done
}
verified_remove() {
    local p=$1
    trust_chain "$p"; present "$p" || return 0
    print -- "Remove: $p"
    if [[ -d $p ]]; then
        tree_check "$p"; /usr/bin/find -P -x "$p" -depth -delete || stop "cannot remove $p"
    else /bin/rm -- "$p" || stop "cannot remove $p"; fi
    present "$p" && stop "still present: $p"
    return 0
}
# The verified one-shot launcher records all three file digests in a fresh
# private directory. Never unlink a replacement or boot out our executing job.
readonly entrypoint=$0
readonly latch=/private/var/db/com.filewave.client-offboarding-4.2.0
readonly activation=/Library/FWUninstaller.sh program=/Library/filewave_uninstaller.sh
readonly launcher=/Library/LaunchDaemons/com.filewave.uninstaller.plist
wrapper_identity() {
    local p digest recorded mode
    [[ $entrypoint == $program ]] || stop 'incorrect Fileset entry point'
    trust_chain "$latch"
    [[ -d $latch && $(/usr/bin/stat -f %p "$latch") == 40700 ]] || stop 'one-shot admission missing'
    for p in "$activation" "$launcher" "$program"; do
        trust_chain "$p"; trust_chain "$latch/${p:t}.sha256"
        case $p in "$activation") mode=100744;; "$launcher") mode=100600;; *) mode=100500;; esac
        [[ -f $p && $(/usr/bin/stat -f '%u:%g:%l:%p' "$p") == "$TRUST_UID:$WHEEL_GID:1:$mode" && -f "$latch/${p:t}.sha256" ]] || stop "unexpected staging identity: $p"
        digest=$(/usr/bin/shasum -a 256 < "$p") && recorded=$(<"$latch/${p:t}.sha256") && [[ $digest == "$recorded" ]] || stop "staging digest mismatch: $p"
    done
}
finish_wrapper() {
    wrapper_identity
    verified_remove "$activation"; verified_remove "$launcher"; verified_remove "$program"
    print -- 'RESULT=0: verified Fileset staging removed; one-shot result retained.'
}
(( EUID == 0 )) || stop 'root required'
umask 077
wrapper_identity
setopt NO_CLOBBER
exec > "$latch/result.log" 2>&1 || stop 'result already exists or cannot create it'
inventory; check_roles; quiescent
main_expected=0
if has_receipt "$MAIN"; then
    main_expected=1
    client_plan
    client_jobs check
else
    for p in /usr/local/sbin/FileWave.app /Library/LaunchDaemons/com.filewave.fwcld.plist /Library/LaunchAgents/com.filewave.kiosk2.plist '/usr/local/sbin/Client Assistant.app'; do
        trust_chain "$p"; present "$p" && stop "unreceipted Client artifact: $p"
    done
    client_job system/com.filewave.fwcld; [[ $cj == absent ]] || stop 'unreceipted Client job'
    process_absent fwcld
fi
retire_upgrader
inventory; check_roles
if has_receipt "$MAIN"; then (( main_expected )) || stop 'main receipt appeared during retirement'; else (( ! main_expected )) || stop 'main receipt disappeared during retirement'; fi
if ! has_receipt "$MAIN"; then
    print -- 'No main Client receipt; checked only the separate upgrader. Its log is retained. Main Client removal is not certified.'
    finish_wrapper
    exit 0
fi
quiescent; check_roles
client_jobs unload
upgrader_absent; quiescent
client_jobs absent
for proc in OSXvnc-server fwGUI fwcld filewave-vnc-server 'FileWave Kiosk' 'Client Assistant'; do process_absent "$proc"; done
for p in "${client_files[@]}"; do verified_remove "$p"; done
for p in "${data_leaves[@]}"; do
    [[ ${p:h} == /private/var/FileWave ]] || stop 'unexpected Client state parent'
    trust_chain "${p:h}"
    if present "$p"; then
        [[ ! -L $p && -f $p && $(/usr/bin/stat -f %u "$p") == $TRUST_UID ]] || stop "Client data type changed: $p"
        /bin/rm -- "$p" || stop "cannot unlink Client state: $p"
    fi
    present "$p" && stop "Client state remains: $p"
done
client_jobs absent
for p in /Library/LaunchAgents/com.filewave.kiosk2.plist '/usr/local/sbin/Client Assistant.app' /usr/local/sbin/FileWave.app /Library/LaunchDaemons/com.filewave.fwcld.plist; do
    trust_chain "$p"; present "$p" && stop "main Client residue: $p (main receipt retained)"
done
for p in "${client_files[@]}"; do
    trust_chain "$p"; present "$p" && stop "Client target reappeared: $p"
done
upgrader_absent; quiescent
/usr/sbin/pkgutil --forget "$MAIN" || stop 'main receipt forget failed'
upgrader_absent; has_receipt "$MAIN" && stop 'main receipt remains'
print -- 'Client and Client Upgrader removed from the verified locations; diagnostics retained. Per-user data and management records were not removed.'

finish_wrapper
exit 0
